/*
 *
 * Copyright Alex Wilkinson
 * Released under New BSD Licence
 *
 */

if (typeof(Cc) == "undefined")
	var Cc = Components.classes;
if (typeof(Ci) == "undefined")
	var Ci = Components.interfaces;
if (typeof(Cu) == "undefined")
	var Cu = Components.utils;

Cu.import("resource://app/jsmodules/StringUtils.jsm");
Cu.import("resource://app/jsmodules/sbProperties.jsm");
Cu.import("resource://app/jsmodules/sbLibraryUtils.jsm");
Components.utils.import("resource://telescope/modules/curRemote.js");


		
var gDaapService = Components.classes["@awilco.net/daapd;1"]
                                 .getService(Components.interfaces.awIHttpRequestHandler).wrappedJSObject;
			
var RemotePage = {};
RemotePage.remoteID = CurrentRemote.id;

RemotePage.load = function() {
	// Set the tab title
	var servicePaneStr = Cc["@mozilla.org/intl/stringbundle;1"]
		.getService(Ci.nsIStringBundleService)
		.createBundle("chrome://newreleases/locale/overlay.properties");
		
	var deck = document.getElementById("remote-page-deck");
	
	if (CurrentRemote.id == null || gDaapService._remotes[CurrentRemote.id] == undefined)
	{
		deck.setAttribute("selectedIndex", 0);
		return;
	}
	if (gDaapService._remotes[RemotePage.remoteID].paired)
	{
		deck.setAttribute("selectedIndex", 2);
	}
	
	document.title = gDaapService._remotes[RemotePage.remoteID].name;
	deck.setAttribute("selectedIndex", 1);
	
	RemotePage.beingPairedCheckLoop();
};

RemotePage.unload = function() { };

RemotePage.pair = function()
{
	//validation
	var promptsService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                   .getService(Components.interfaces.nsIPromptService);
								   
	var txtbox = document.getElementById('remote-pairingcodebox');
	var code = txtbox.value;
	
	if (code.length != 4)
	{
		promptsService.alert(window,'Invalid Code','The code must be 4 digits long');
		return;
	}
	var codeInt = parseInt(code);
	if (!codeInt && code != '0000')
	{
		promptsService.alert(window,'Invalid Code','The code must be 4 numerical digits');
		return;
	}
	
	gDaapService.pairRemote(RemotePage.remoteID,code);
};

RemotePage.beingPairedCheckLoop = function()
{
	this.timer = window.setInterval(RemotePage.pairedCheck,1000);
}
RemotePage.pairedCheck = function()
{
	if (gDaapService._remotes[RemotePage.remoteID].paired)
	{
		var deck = document.getElementById("remote-page-deck");
		deck.setAttribute("selectedIndex", 2);
		window.clearInterval(this.timer);
	}
}
		